<template>
  <div class="wrapper ">
    <el-container class="recharge-transfer-container">
      <el-header>
        <h2 class="title">充值转账</h2>
      </el-header>

      <el-main>
        <!-- 用户信息和余额 -->
        <div class="user-info">
          <h4>
                <span>用户：{{ userName }}</span>
                <span class="balance">钱包余额：{{ amount }}元</span>
                <el-link
                    type="warning"
                @click="showCouponRules()"
                class="coupon-rule-link"
                >
                充值转账必看！
                </el-link>
          </h4>
        </div>
        <!-- 优惠券规则对话框 -->
        <el-dialog
            v-model="couponRulesDialog.show"
            title="充值转账规则"
            width="500"
        >
          <div class="coupon-rules-content">
            <p>***关于充值有礼活动：</p>
            <p>1、为回馈新老业主，新增充值大于等于100元送优惠券活动</p>
            <p>2、优惠券金额为充值金额的10%（且向下取整）</p>
            <p>***关于转账行为：</p>
            <p>3、转账有风险，确认需谨慎</p>
            <p>4、感谢您对该系统的大力支持，祝您使用愉快</p>
            <p style="color: #909399; margin-top: 15px;">* 最终解释权归系统所有</p>
          </div>
          <template #footer>
        <span>
          <el-button @click="couponRulesDialog.show = false">关闭</el-button>
        </span>
          </template>
        </el-dialog>
        <!-- 充值金额选择 -->
        <div class="amount-options">
          <h4>充值金额</h4>
          <div class="amount-buttons">
            <el-button
                v-for="amt in presetAmounts"
                :key="amt"
                :class="{'active-amount': customAmount === amt}"
                @click="selectAmount(amt)"
                :size="amt === '自定义' ? 'small' : 'medium'"
                :plain="amt === '自定义' ? false : true"
                :type="customAmount === amt ? 'primary' : ''"
            >
              {{ amt === '自定义' ? amt : '¥' + amt }}
            </el-button>
            <el-input
                v-if="customAmount === '自定义'"
                v-model="customInput"
                @input="onInput"
                placeholder="请输入金额"
                class="custom-amount-input"
                type="number"
            />
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" class="recharge-btn" @click="openRechargeDialog()">充值</el-button>
          <el-button type="warning" class="transfer-btn" @click="openTransferDialog()">转账</el-button>
        </div>
      </el-main>
    </el-container>

    <!-- 充值对话框 -->
    <el-dialog
        v-model="rechargeDialog.show"
        title="确认充值"
        center
        width="400"
        :close-on-click-modal="false"
    >
      <div class="recharge-content">
        <p>支付方式：<strong>{{ paymentMethod }}</strong></p>
        <p>充值金额：<strong>{{ rechargeAmount }}元</strong></p>
        <p>充值后余额：<strong>{{ newBalance }}元</strong></p>
        <p>请扫码支付:</p>
        <img src="@/components/icons/user/rechargeimg.jpg" alt="支付二维码" style="width: 200px; height: 200px; margin: 20px auto; display: block;" />
      </div>
      <template #footer>
        <span>
          <el-button @click="rechargeDialog.show = false">取消</el-button>
          <el-button type="primary" @click="handleRecharge()">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 转账对话框 -->
    <el-dialog
        v-model="transferDialog.show"
        title="确认转账"
        center
        width="500"
        :close-on-click-modal="false"
    >
      <el-form ref="transferFormRef" :model="transferForm" :rules="transferRules">
        <div class="transfer-content">
          <el-form-item label="对方手机号" prop="tophone">
            <el-input v-model="transferForm.tophone" placeholder="请输入对方手机号" @input="formatPhoneNumber" />
          </el-form-item>
          <el-form-item label="转账金额" prop="transferAmount">
            <el-input
                v-model="transferForm.transferAmount"
                placeholder="请输入转账金额"
                @input="transferInput"
            />
          </el-form-item>
          <p>为了验证你是否是本人,请输入验证码</p>
          <el-form-item style="display: flex; margin-top: 20px;">
            <el-input v-model="verifyCode" placeholder="验证码" style="width: 40%; margin-right: 20px;" />
            <el-link @click="sendVerifyCode()">发送验证码</el-link>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span>
          <el-button  @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleTransfer()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getCookieForObject, setCookiesFromObject } from '@/util';
import { post, get } from '@/plugins/axios';

// 页面状态
const rechargeDialog = ref({ show: false });
const transferDialog = ref({ show: false });
const amount = ref(0);
const userName = ref('');
const customAmount = ref(100); // 默认为50元
const customInput = ref('');
const couponRulesDialog = ref({ show: false }); // 新增优惠券规则对话框
const paymentMethod = ref('wechat');
const verifyCode = ref('');
const transferForm = reactive({
  tophone: '',
  transferAmount: ''
});
const transferFormRef = ref(null);
//const amountToTransfer = parseFloat(transferForm.transferAmount);
// 预设充值金额
const presetAmounts = [100, 500, 1000, 5000, 10000, '自定义'];

// 计算属性
const rechargeAmount = computed(() => {
  return customAmount.value === '自定义' ? customInput.value : customAmount.value;
});

// 显示优惠券规则
function showCouponRules() {
  couponRulesDialog.value.show = true;
}

// 处理充值 - 新增赠送优惠券逻辑
function handleRecharge() {
  const user = getCookieForObject('user');
  const rechargeValue = parseFloat(rechargeAmount.value);

  post('/tUser/recharge', {
    id: user.id,
    value: rechargeValue
  }, res => {
    if (res) {
      rechargeDialog.value.show = false;
      user.account = newBalance.value;
      setCookiesFromObject('user', user);
      initUserInfo();

      // 充值成功后检查是否赠送优惠券
      if (rechargeValue >= 100) {
        const couponAmount = Math.floor(rechargeValue * 0.1); // 计算赠送金额（取整）
        if (couponAmount > 0) {
          giveCoupon(user.id, couponAmount); // 调用赠送优惠券接口
        }
      }

      ElMessage.success(`充值 ${rechargeValue} 元成功！`);
      customAmount.value = 100;
    } else {
      ElMessage.error('充值失败，请稍后再试');
    }
  });
}

// 赠送优惠券
function giveCoupon(userId, amount) {
  post('/coupon/give', {
    userId,
    amount
  }, couponRes => {
    console.log(couponRes)
    if (couponRes) {
      ElMessage.success(`成功获得${amount}元优惠券！`);
    } else {
      ElMessage.warning('获取优惠券失败');
    }
  });
}

// 计算优惠券过期时间（30天后）
function getExpiredTime() {
  const today = new Date();
  today.setDate(today.getDate() + 30);
  return today.toISOString().split('T')[0]; // 格式化为YYYY-MM-DD
}


const newBalance = computed(() => {
  return (parseFloat(amount.value) + parseFloat(rechargeAmount.value)).toFixed(2);
});

// 初始化
onMounted(() => {
  initUserInfo();
});
function handleCancel() {
  console.log('取消按钮被点击');
  transferDialog.value.show = false;
}
function initUserInfo() {
  const user = getCookieForObject('user');
  if (user) {
    amount.value = parseFloat(user.account);
    userName.value = user.nickName || user.username || '用户';
  }
}
// 添加手机号格式化函数
function formatPhoneNumber(e) {
  // 只允许输入数字
  transferForm.tophone = e.target.value.replace(/[^\d]/g, '');
}
// 金额输入验证
function onInput(e) {
  const regex = /^\D*([0-9]\d*\.?\d{0,2})?.*$/;
  customInput.value = String(customInput.value).replace(regex, '$1');
}

// 转账金额输入处理（已有函数，但需要修复）
function transferInput(e) {
  let inputValue = e.target.value;

  // 过滤非数字和小数点
  inputValue = inputValue.replace(/[^\d.]/g, '');
  // 过滤开头的小数点
  inputValue = inputValue.replace(/^\./, '');
  // 过滤多个小数点
  inputValue = inputValue.replace(/\.{2,}/, '.');
  // 确保只有一个小数点
  inputValue = inputValue.replace(/(\..*)\./, '$1');
  // 限制小数位数为两位
  if (inputValue.includes('.')) {
    const parts = inputValue.split('.');
    if (parts[1].length > 2) {
      inputValue = parts[0] + '.' + parts[1].substring(0, 2);
    }
  }

  // 限制最大金额为1000000
  if (parseFloat(inputValue) > 1000000) {
    inputValue = '1000000';
  }

  // 同步更新响应式数据
  transferForm.transferAmount = inputValue;
}

// 选择预设金额
function selectAmount(amt) {
  if (amt === '自定义') {
    customAmount.value = amt;
    // 清空输入框
    customInput.value = '';
  } else {
    customAmount.value = amt;
    customInput.value = '';
  }
}

// 打开充值对话框
function openRechargeDialog() {
  if (customAmount.value === '自定义' && !customInput.value) {
    ElMessage.error('请输入自定义金额');
    return;
  }

  if (parseFloat(rechargeAmount.value) <= 0) {
    ElMessage.error('请输入正确的充值金额');
    return;
  }

  rechargeDialog.value.show = true;
}

// // 处理充值
// function handleRecharge() {
//   const user = getCookieForObject('user');
//   post('/tUser/recharge', {
//     id: user.id,
//     value: rechargeAmount.value
//   }, res => {
//     if (res) {
//       rechargeDialog.value.show = false;
//       user.account = newBalance.value;
//       setCookiesFromObject('user', user);
//       initUserInfo(); // 刷新余额
//       ElMessage.success(`充值 ${rechargeAmount.value} 元成功！`);
//       customAmount.value = 50; // 重置为默认金额
//     } else {
//       ElMessage.error('充值失败，请稍后再试');
//     }
//   });
// }

// 打开转账对话框
function openTransferDialog() {
  transferDialog.value.show = true;
  verifyCode.value = '';
}

// 发送验证码
function sendVerifyCode() {
  const user = getCookieForObject('user');
  post("/tUser/sendVerificationCode", { email: user.email }, content => {
    if (content) {
      ElMessage.success('验证码发送成功');
    } else {
      ElMessage.error('验证码发送失败');
    }
  });
}

//处理转账
function handleTransfer() {
  // transferFormRef.value.validate((valid) => {
  //   if (valid) {
      post("/tUser/verifyCode", {
        email: getCookieForObject('user').email,
        code: verifyCode.value
      }, verifyRes => {
        if (verifyRes) {
          post("/tUser/transfer", {
            id: getCookieForObject('user').id,
            tophone: transferForm.tophone,
            transferAmount: transferForm.transferAmount,
           // transferAmount: amountToTransfer // 传递数值类型
          }, transferRes => {
            console.log(transferRes);

            if (transferRes) {


              amount.value = (parseFloat(amount.value) - parseFloat(transferForm.transferAmount)).toFixed(2);
              const user = getCookieForObject('user');
              user.account = amount.value;
              setCookiesFromObject('user', user);
              ElMessage.success('转账成功！');

              // 关闭对话框
              transferDialog.value.show = false;

            } else {
              ElMessage.error('转账失败，请稍后再试');
            }
          });
        } else {
          ElMessage.error('验证码错误');
        }
      });
  //   } else {
  //     ElMessage.error('请检查表单');
  //     return false;
  //   }
  // });
}

// 转账表单验证规则
const transferRules = {
  tophone: [
    { required: true, message: '请输入对方手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号格式错误', trigger: 'blur' },
    { validator: checkPhone, trigger: 'blur' }
  ],
  transferAmount: [
    { required: true, message: '请输入转账金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入转账金额'));
        } else if (isNaN(parseFloat(value)) || parseFloat(value) <= 0) {
          callback(new Error('请输入正数金额'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 检查手机号是否注册
function checkPhone(rule, value, callback) {
  get("/tUser/check", { id: getCookieForObject('user').id, value, field: 'phone' }, res => {
    if (!res) {
      if (value === getCookieForObject('user').phone) {
        callback(new Error('不能转账给自己'));
      } else {
        callback();
      }
    } else {
      callback(new Error('该手机号未注册'));
    }
  });
}
</script>

<style lang="scss" scoped>
.wrapper {
  height: 100% !important;
  background-color: #fff5e9;
  border-radius: 8px;
  padding: 20px;
  box-sizing: border-box;
}

// 新增优惠券规则对话框样式
.coupon-rules-content {
  padding: 20px;
  line-height: 1.8;
  font-size: 14px;
}
.coupon-rule-link {
  font-weight: bold;
  font-size: 20px;
  text-decoration: none;
  padding-left: 35px;

  &:hover {
    text-decoration: underline;
  }
}
.recharge-transfer-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px;

  .title {
    font-size: 24px;
    color: #333;
    text-align: center;
    margin-bottom: 30px;
  }

  .user-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 30px;

    h4 {
      margin: 0;
      font-size: 16px;

      .balance {
        color: #f56c6c;
        font-weight: bold;
        margin-left: 20px;
      }
    }
  }

  .amount-options {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 30px;

    h4 {
      margin: 0 0 20px 0;
      font-size: 16px;
    }

    .amount-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;

      .el-button {
        min-width: 80px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .custom-amount-input {
        width: 120px;
        height: 40px;
        margin-top: 0;
      }
    }
  }

  .action-buttons {
    display: flex;
    gap: 20px;
    justify-content: center;

    .recharge-btn, .transfer-btn {
      min-width: 150px;
      background-color: #f39d33;
      border-color:#F39D33FF;
      height: 50px;
      font-size: 16px;
      &:hover {
        background-color: #d78219;
        border-color: #d88a10;
      }
    }

    .transfer-btn {
      background-color: #9ed237;
      border-color: #90c921;
      color: #fff;

      &:hover {
        background-color: #79ad15;
        border-color: #6d9b11;
      }
    }
  }
}

// 对话框样式
.recharge-content, .transfer-content {
  padding: 20px;

  p {
    margin-bottom: 15px;
    font-size: 16px;

    strong {
      color: #303133;
      font-weight: bold;
    }
  }

  h3 {
    margin-bottom: 20px;
    font-size: 18px;
  }
}
.el-dialog__body {
  max-height: 400px; /* 设置对话框内容最大高度 */
  overflow-y: auto; /* 必要时显示滚动条 */
}
// 金额选择样式
.active-amount {
  background-color: #f39d33 !important;
  color: #fff !important;
}
</style>